import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // 全局状态
        currentUser: null,
        isAuthenticated: false,
        favorites: []
    },
    mutations: {
        // 修改状态的同步方法
        SET_CURRENT_USER(state, user) {
            state.currentUser = user
            state.isAuthenticated = !!user
        },
        ADD_FAVORITE(state, website) {
            state.favorites.push(website)
        },
        REMOVE_FAVORITE(state, websiteId) {
            state.favorites = state.favorites.filter(site => site.id !== websiteId)
        }
    },
    actions: {
        // 可以包含异步操作的方法
        login({ commit }, userData) {
            // 这里可以添加实际的登录逻辑，如API请求
            return new Promise((resolve) => {
                setTimeout(() => {
                    const user = { id: 1, username: userData.username }
                    commit('SET_CURRENT_USER', user)
                    resolve(user)
                }, 1000)
            })
        },
        logout({ commit }) {
            commit('SET_CURRENT_USER', null)
        },
        toggleFavorite({ commit, state }, website) {
            const isFavorite = state.favorites.some(site => site.id === website.id)
            if (isFavorite) {
                commit('REMOVE_FAVORITE', website.id)
            } else {
                commit('ADD_FAVORITE', website)
            }
        }
    },
    getters: {
        // 从状态派生的计算属性
        isAuthenticated: state => state.isAuthenticated,
        currentUser: state => state.currentUser,
        favorites: state => state.favorites,
        isFavorite: state => websiteId => {
            return state.favorites.some(site => site.id === websiteId)
        }
    }
})